package com.view.jameson.library;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;


public class BannerScaleHelper {
    private BannerRecyclerView mRecyclerView;
    private Context mContext;

    private float mScale = 0.9f; // 两边视图scale
    private int mPagePadding = BannerAdapterHelper.sPagePadding; // 卡片的padding, 卡片间的距离等于2倍的mPagePadding
    private int mShowLeftCardWidth = BannerAdapterHelper.sShowLeftCardWidth;   // 左边卡片显示大小

    private int mCardWidth; // 卡片宽度
    private int mOnePageWidth; // 滑动一页的距离
    private int mCardGalleryWidth;

    private int mFirstItemPos;
    private int mCurrentItemOffset;

    private CardLinearSnapHelper mLinearSnapHelper = new CardLinearSnapHelper();
    private int mLastPos;

    public void attachToRecyclerView(final BannerRecyclerView mRecyclerView) {
        if (mRecyclerView == null) {
            return;
        }
        this.mRecyclerView = mRecyclerView;
        mContext = mRecyclerView.getContext();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // Log.e("TAG", "RecyclerView.OnScrollListener onScrollStateChanged");
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mLinearSnapHelper.mNoNeedToScroll = getCurrentItem() == 0 ||
                            getCurrentItem() == 2 ||
                            getCurrentItem() == 3 ||
                            getCurrentItem() == mRecyclerView.getAdapter().getItemCount() - 2;
                    if (mLinearSnapHelper.finalSnapDistance[0] == 0
                            && mLinearSnapHelper.finalSnapDistance[1] == 0) {
                        mCurrentItemOffset = 0;
                        mLastPos = getCurrentItem();
                        //认为是一次滑动停止 这里可以写滑动停止回调
                        mRecyclerView.dispatchOnPageSelected(mLastPos);
                        //Log.e("TAG", "滑动停止后最终位置为" + getCurrentItem());
                    }
                } else {
                    mLinearSnapHelper.mNoNeedToScroll = false;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //Log.e("TAG", String.format("onScrolled dx=%s, dy=%s", dx, dy));
                super.onScrolled(recyclerView, dx, dy);
                // dx>0则表示右滑, dx<0表示左滑, dy<0表示上滑, dy>0表示下滑
                mCurrentItemOffset += dx;
                onScrolledChangedCallback();
            }
        });
        initWidth();
        mLinearSnapHelper.attachToRecyclerView(mRecyclerView);
    }

    /**
     * 初始化卡片宽度
     */
    private void initWidth() {
        mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mRecyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mCardGalleryWidth = mRecyclerView.getWidth();
                mCardWidth = mCardGalleryWidth - ScreenUtil.dip2px(mContext, 2 * (mPagePadding + mShowLeftCardWidth));
//                mCardWidth =  ScreenUtil.dip2px(mContext, 1000);
                mOnePageWidth = mCardWidth;
                scrollToPosition(mFirstItemPos);
            }
        });
    }

    public void setCurrentItem(int item) {
        setCurrentItem(item,false);
    }

    public void setCurrentItem(int item, boolean smoothScroll) {
        if (mRecyclerView == null) {
            return;
        }
        if (smoothScroll) {
            mRecyclerView.smoothScrollToPosition(item);
        }else {
            scrollToPosition(item);
        }
    }

    public void scrollToPosition(int pos) {
        if (mRecyclerView == null) {
            return;
        }
        //mRecyclerView.getLayoutManager()).scrollToPositionWithOffset 方法不会回调  RecyclerView.OnScrollListener 的onScrollStateChanged方法,是瞬间跳到指定位置
        //mRecyclerView.smoothScrollToPosition 方法会回调  RecyclerView.OnScrollListener 的onScrollStateChanged方法 并且是自动居中，有滚动过程的滑动到指定位置
        ((LinearLayoutManager) mRecyclerView.getLayoutManager()).
                scrollToPositionWithOffset(pos,
                        ScreenUtil.dip2px(mContext, mPagePadding + mShowLeftCardWidth-15));
        mCurrentItemOffset = 0;
        mLastPos = pos;
        //认为是一次滑动停止 这里可以写滑动停止回调
        mRecyclerView.dispatchOnPageSelected(mLastPos);
        //onScrolledChangedCallback();
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                onScrolledChangedCallback();
            }
        });
    }

    public void setFirstItemPos(int firstItemPos) {
        this.mFirstItemPos = firstItemPos;
    }


    /**
     * RecyclerView位移事件监听, view大小随位移事件变化
     */
    private void onScrolledChangedCallback() {
        if (mOnePageWidth == 0) {
            return;
        }
        int currentItemPos = getCurrentItem();
        int offset = mCurrentItemOffset - (currentItemPos - mLastPos) * mOnePageWidth;
        float percent = (float) Math.max(Math.abs(offset) * 1.0 / mOnePageWidth, 0.0001);

        Log.e("TAG2121",String.format("offset=%s, percent=%s", offset, percent));
        View leftView1 = null;
        View leftView2 = null;
        View currentView;
        View rightView1 = null;
        View rightView2 = null;
        int itemCount = mRecyclerView.getAdapter().getItemCount() - 2;
        if (currentItemPos > 0) {
            leftView1 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos - 1);
            leftView2 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos - 2);
        }
        currentView = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos);
        if (currentItemPos < mRecyclerView.getAdapter().getItemCount() - 1) {
            rightView1 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos + 1);
        }
        if (currentItemPos < mRecyclerView.getAdapter().getItemCount() - 2) {
            rightView2 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos + 2);
        }
        float scalex = 1f;
//        float scaley=(1 - mScale) * percent + mScale;
        float scaley = 1;
//        float scaley=0.9f;
//        Log.e("scaleyscaley", scaley + "==");
        if (leftView1 != null) {
            Log.e("是否为空", "leftView1不为空");
            // y = (1 - mScale)x + mScale
//            leftView1.setScaleY((1 - mScale) * percent + mScale);
            leftView1.setScaleX(scalex);
            leftView1.setScaleY(scaley);

            if (itemCount == 0 || itemCount == 1 || itemCount == 2 || itemCount == 3) {
                leftView1.setBackground(null);

                if (itemCount == 1) {
                    setMargins(leftView1, 100, 30, 5, 30);
                } else if (itemCount == 2) {
                    setMargins(leftView1, 100, 30, 5, 30);
                } else if (itemCount == 3) {
                    setMargins(leftView1, 90, 30, 5, 30);
                } else {
                    setMargins(leftView1, 5, 30, 5, 30);
                }
            } else {
                leftView1.setBackground(mContext.getDrawable(R.drawable.shape_a1a0a5_storke_2_r8));
                setMargins(leftView1, 5, 30, 5, 30);
            }

        } else {
            Log.e("是否为空", "leftView1为空");
        }
        if (leftView2 != null) {
            Log.e("是否为空", "leftView2不为空");
            // y = (1 - mScale)x + mScale
//            leftView2.setScaleY((1 - mScale) * percent + mScale);
            leftView2.setScaleX(scalex);
            leftView2.setScaleY(scaley);

            if (itemCount == 0 || itemCount == 1 || itemCount == 2 || itemCount == 3) {
                leftView2.setBackground(null);

                if (itemCount == 1) {
                    setMargins(leftView2, 100, 30, 5, 30);
                } else {
                    setMargins(leftView2, 5, 30, 5, 30);
                }
            } else {
                leftView2.setBackground(mContext.getDrawable(R.drawable.shape_a1a0a5_storke_2_r8));
                setMargins(leftView2, 5, 30, 5, 30);
            }

        } else {
            Log.e("是否为空", "leftView2为空");
        }
        if (currentView != null) {
            // y = (mScale - 1)x + 1
//            currentView.setScaleY((mScale - 1) * percent + 1);
//            currentView.setScaleX((float) ((mScale - 1) * percent + 1));
//            currentView.setBackground(mContext.getDrawable(R.drawable.shape_e4e4e4_424243_storke_r4));
//            currentView.setScaleX(scalex);
//            currentView.setScaleY((mScale - 1) * percent + 1);
            if (itemCount != 0) {
                currentView.setBackground(mContext.getDrawable(R.drawable.shape_f80069_storke_2_r8));
            }
            currentView.setScaleX(1.2f);
            currentView.setScaleY(1.2f);
//            AnimatorSet animatorSet = new AnimatorSet();
//            currentView.setPivotX(currentView.getWidth() / 2);
//            currentView.setPivotY(currentView.getHeight() / 2);
//            animatorSet.playTogether(
//                    ObjectAnimator.ofFloat(currentView, "scaleX", 1, 1.2f).setDuration(100),
//                    ObjectAnimator.ofFloat(currentView, "scaleY", 1, 1.2f).setDuration(100));

//            if (mList.size()==2){
//                setMargins(currentView, 110, 30, 120, 30);
//            }else {
            setMargins(currentView, 30, 30, 30, 30);
//            }

//            animatorSet.start();
        }
        if (rightView1 != null) {
            Log.e("是否为空", "rightView1不为空");
            // y = (1 - mScale)x + mScale
//            rightView1.setScaleY((1 - mScale) * percent + mScale);
            rightView1.setScaleX(scalex);
            rightView1.setScaleY(scaley);
            if (itemCount == 0 || itemCount == 1 || itemCount == 2 || itemCount == 3) {
                rightView1.setBackground(null);
                if (itemCount == 1) {
                    setMargins(rightView1, 5, 30, 100, 30);
                } else if (itemCount == 2) {
                    setMargins(rightView1, 5, 30, 120, 30);
                } else if (itemCount == 3) {
                    setMargins(rightView1, 5, 30, 5, 30);
                } else {
                    setMargins(rightView1, 5, 30, 5, 30);
                }
            } else {
                rightView1.setBackground(mContext.getDrawable(R.drawable.shape_a1a0a5_storke_2_r8));
                setMargins(rightView1, 5, 30, 5, 30);
            }

        } else {
            Log.e("是否为空", "rightView1为空");
        }
        if (rightView2 != null) {
            Log.e("是否为空", "rightView2不为空");
            // y = (1 - mScale)x + mScale
//            rightView2.setScaleY((1 - mScale) * percent + mScale);
            rightView2.setScaleX(scalex);
            rightView2.setScaleY(scaley);
            if (itemCount == 0 || itemCount == 1 || itemCount == 2 || itemCount == 3) {
                rightView2.setBackground(null);
                if (itemCount == 1) {
                    setMargins(rightView2, 5, 30, 100, 30);
                } else if (itemCount == 3) {
                    setMargins(rightView2, 5, 30, 5, 30);
                } else {
                    setMargins(rightView2, 5, 30, 5, 30);
                }
            } else {
                rightView2.setBackground(mContext.getDrawable(R.drawable.shape_a1a0a5_storke_2_r8));
                setMargins(rightView2, 5, 30, 5, 30);
            }

        } else {
            Log.e("是否为空", "rightView2为空");
        }

        if (leftView1 != null && leftView2 != null && rightView1 != null && rightView2 == null) {
            setMargins(leftView1, 5, 30, 5, 30);
        }
    }



//    /**
//     * RecyclerView位移事件监听, view大小随位移事件变化
//     */
//    private void onScrolledChangedCallback() {
//        if (mOnePageWidth == 0) {
//            return;
//        }
//        int currentItemPos = getCurrentItem();
//        int offset = mCurrentItemOffset - (currentItemPos - mLastPos) * mOnePageWidth;
//        float percent = (float) Math.max(Math.abs(offset) * 1.0 / mOnePageWidth, 0.0001);
//
//        Log.e("TAG2121",String.format("offset=%s, percent=%s", offset, percent));
//        View leftView1 = null;
//        View leftView2 = null;
//        View currentView;
//        View rightView1 = null;
//        View rightView2 = null;
//        int itemCount = mRecyclerView.getAdapter().getItemCount() - 2;
//        if (currentItemPos > 0) {
//            leftView1 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos - 1);
//            leftView2 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos - 2);
//        }
//        currentView = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos);
//        if (currentItemPos < mRecyclerView.getAdapter().getItemCount() - 1) {
//            rightView1 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos + 1);
//        }
//        if (currentItemPos < mRecyclerView.getAdapter().getItemCount() - 2) {
//            rightView2 = mRecyclerView.getLayoutManager().findViewByPosition(currentItemPos + 2);
//        }
//        float scalex = 1f;
////        float scaley=(1 - mScale) * percent + mScale;
//        float scaley = 1;
////        float scaley=0.9f;
////        Log.e("scaleyscaley", scaley + "==");
//        if (leftView1 != null) {
//            Log.e("是否为空", "leftView1不为空");
//            // y = (1 - mScale)x + mScale
////            leftView1.setScaleY((1 - mScale) * percent + mScale);
//            leftView1.setScaleX(scalex);
//            leftView1.setScaleY(scaley);
//
//
//        } else {
//            Log.e("是否为空", "leftView1为空");
//        }
//        if (leftView2 != null) {
//            Log.e("是否为空", "leftView2不为空");
//            // y = (1 - mScale)x + mScale
////            leftView2.setScaleY((1 - mScale) * percent + mScale);
//            leftView2.setScaleX(scalex);
//            leftView2.setScaleY(scaley);
//
//        } else {
//            Log.e("是否为空", "leftView2为空");
//        }
//        if (currentView != null) {
//            // y = (mScale - 1)x + 1
////            currentView.setScaleY((mScale - 1) * percent + 1);
////            currentView.setScaleX((float) ((mScale - 1) * percent + 1));
////            currentView.setBackground(mContext.getDrawable(R.drawable.shape_e4e4e4_424243_storke_r4));
////            currentView.setScaleX(scalex);
////            currentView.setScaleY((mScale - 1) * percent + 1);
//            if (itemCount != 0) {
//                currentView.setBackground(mContext.getDrawable(R.drawable.shape_f80069_storke_2_r8));
//            }
//            currentView.setScaleX(1.2f);
//            currentView.setScaleY(1.2f);
//
//        }
//        if (rightView1 != null) {
//            Log.e("是否为空", "rightView1不为空");
//            // y = (1 - mScale)x + mScale
////            rightView1.setScaleY((1 - mScale) * percent + mScale);
//            rightView1.setScaleX(scalex);
//            rightView1.setScaleY(scaley);
//
//
//        } else {
//            Log.e("是否为空", "rightView1为空");
//        }
//        if (rightView2 != null) {
//            Log.e("是否为空", "rightView2不为空");
//            // y = (1 - mScale)x + mScale
////            rightView2.setScaleY((1 - mScale) * percent + mScale);
//            rightView2.setScaleX(scalex);
//            rightView2.setScaleY(scaley);
//
//        } else {
//            Log.e("是否为空", "rightView2为空");
//        }
//
////        if (leftView1 != null && leftView2 != null && rightView1 != null && rightView2 == null) {
////            setMargins(leftView1, 5, 30, 5, 30);
////        }
//    }



    private void setMargins(View currentView, int left, int top, int right, int bottom) {
//        ViewGroup.LayoutParams layoutParams = currentView.getLayoutParams();
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) currentView.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.setMargins(left, top, right, bottom);
            currentView.setLayoutParams(layoutParams);
        }
    }

    public int getCurrentItem() {
        //return ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findLastVisibleItemPosition() - 1;
        return mRecyclerView.getLayoutManager().getPosition(mLinearSnapHelper.findSnapView(mRecyclerView.getLayoutManager()));
    }

    public void setScale(float scale) {
        mScale = scale;
    }

    public void setPagePadding(int pagePadding) {
        mPagePadding = pagePadding;
    }

    public void setShowLeftCardWidth(int showLeftCardWidth) {
        mShowLeftCardWidth = showLeftCardWidth;
    }

    /**
     * 防止卡片在第一页和最后一页因无法"居中"而一直循环调用onScrollStateChanged-->SnapHelper.snapToTargetExistingView-->onScrollStateChanged
     * Created by jameson on 9/3/16.
     */
    private static class CardLinearSnapHelper extends LinearSnapHelper {
        public boolean mNoNeedToScroll = false;
        public int[] finalSnapDistance = {0, 0};

        @Override
        public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) {
            //Log.e("TAG", "calculateDistanceToFinalSnap");
            if (mNoNeedToScroll) {
                finalSnapDistance[0] = 0;
                finalSnapDistance[1] = 0;
            } else {
                finalSnapDistance = super.calculateDistanceToFinalSnap(layoutManager, targetView);
            }
            return finalSnapDistance;
        }
    }
}
